package com.m3958.firstgwt.server.service;

import java.io.IOException;
import java.io.StringReader;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.base.Charsets;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.dao.FtlDao;
import com.m3958.firstgwt.server.model.Ftl;

import freemarker.template.Configuration;
import freemarker.template.Template;


@Singleton
public class DbtplCacher{
	
	private LoadingCache<String, Template> templates;
	
	@Inject
	private FtlDao ftlDao;
	
	public DbtplCacher(){
		templates = CacheBuilder.newBuilder()
			       .maximumSize(50)
			       .refreshAfterWrite(5, TimeUnit.MINUTES)
			       .build(
			           new CacheLoader<String, Template>() {
			             public Template load(String key) throws IOException{
			         		Ftl ftl = ftlDao.find(Integer.valueOf(key));
			        		Template template = new Template(key, new StringReader(ftl.getFtl()), new Configuration(), Charsets.UTF_8.name());
			        		return template;

			             }
			           });
	}
	
	
	public Template get(String key) throws ExecutionException{
			return templates.get(key);
	}
	
	public void invalidate(int key){
		templates.invalidate(key + "");
	}

}
